#nullable enable
using Godot;
using System.Linq;
using AndroidUnevenRoadGame.Game;

namespace AndroidUnevenRoadGame.UI
{
	public partial class VictoryScene : Control
	{
		[Export] private Label? _titleLabel;
		[Export] private Label? _goldLabel;
		[Export] private VBoxContainer? _cardContainer;
		[Export] private Button? _skipCardButton;
		[Export] private Button? _continueButton;
		[Export] private VBoxContainer? _potionContainer;
		[Export] private VBoxContainer? _relicContainer;
		[Export] private Label? _messageLabel;

		private RewardSystem.RewardBundle? _bundle;
		private bool _cardChoiceResolved;
		private bool _potionClaimed;
		private bool _relicClaimed;

		public override void _Ready()
		{
			_titleLabel ??= GetNodeOrNull<Label>("Panel/Root/Title");
			_goldLabel ??= GetNodeOrNull<Label>("Panel/Root/GoldLabel");
			_cardContainer ??= GetNodeOrNull<VBoxContainer>("Panel/Root/ContentScroll/Content/CardSection/CardList");
			_skipCardButton ??= GetNodeOrNull<Button>("Panel/Root/ContentScroll/Content/CardSection/SkipButton");
			_continueButton ??= GetNodeOrNull<Button>("Panel/Root/ContinueButton");
			_potionContainer ??= GetNodeOrNull<VBoxContainer>("Panel/Root/ContentScroll/Content/PotionSection");
			_relicContainer ??= GetNodeOrNull<VBoxContainer>("Panel/Root/ContentScroll/Content/RelicSection");
			_messageLabel ??= GetNodeOrNull<Label>("Panel/Root/MessageLabel");

			if (_continueButton != null)
			{
				_continueButton.Pressed += OnContinuePressed;
			}

			if (_skipCardButton != null)
			{
				_skipCardButton.Pressed += OnSkipCardPressed;
			}

			RenderRewards();
		}

		private void RenderRewards()
		{
			_bundle = RewardSystem.RewardStore.Current;
			if (_bundle == null)
			{
				_messageLabel?.Set("text", "未找到战斗奖励。");
				return;
			}

			if (_titleLabel != null)
			{
				_titleLabel.Text = $"第 {GameRoot.Instance.CurrentFloor - 1} 层战斗胜利";
			}

			if (_goldLabel != null)
			{
				_goldLabel.Text = $"当前金币：{GameRoot.Instance.PlayerGold}";
			}

			RenderCardRewards();
			RenderPotionReward();
			RenderRelicReward();
			UpdateContinueButtonState();
		}

		private void RenderCardRewards()
		{
			if (_cardContainer == null || _bundle == null)
			{
				return;
			}

			foreach (Node child in _cardContainer.GetChildren())
			{
				child.QueueFree();
			}

			if (_bundle.Cards.Count == 0)
			{
				var label = new Label
				{
					Text = "本次未掉落卡牌。"
				};
				_cardContainer.AddChild(label);
				_cardChoiceResolved = true;
				_skipCardButton?.Set("visible", false);
				return;
			}

			foreach (var card in _bundle.Cards)
			{
				var button = new Button
				{
					Text = $"{card.Name}｜{card.Type}｜能量 {card.Cost}\n{card.Description}",
					SizeFlagsHorizontal = SizeFlags.ExpandFill
				};

				button.Pressed += () => OnCardSelected(card, button);
				_cardContainer.AddChild(button);
			}
		}

		private void RenderPotionReward()
		{
			if (_potionContainer == null || _bundle == null)
			{
				return;
			}

			foreach (Node child in _potionContainer.GetChildren())
			{
				child.QueueFree();
			}

			if (string.IsNullOrEmpty(_bundle.PotionId))
			{
				_potionContainer.Visible = false;
				return;
			}

			var potion = PotionDatabase.Get(_bundle.PotionId);
			var button = new Button
			{
				Text = $"{potion.Name}\n{potion.Description}"
			};

			button.Pressed += () => OnPotionClaimed(button, potion);
			_potionContainer.AddChild(new Label { Text = "药剂掉落：" });
			_potionContainer.AddChild(button);
		}

		private void RenderRelicReward()
		{
			if (_relicContainer == null || _bundle == null)
			{
				return;
			}

			foreach (Node child in _relicContainer.GetChildren())
			{
				child.QueueFree();
			}

			if (string.IsNullOrEmpty(_bundle.RelicId))
			{
				_relicContainer.Visible = false;
				return;
			}

			var relic = RelicDatabase.Get(_bundle.RelicId);
			var button = new Button
			{
				Text = $"{relic.Name}\n{relic.Description}"
			};

			button.Pressed += () => OnRelicClaimed(button, relic);
			_relicContainer.AddChild(new Label { Text = "遗物掉落：" });
			_relicContainer.AddChild(button);
		}

		private void OnCardSelected(CardDefinition card, Button button)
		{
			var player = GameRoot.Instance.Player;
			player.AddCardToDeck(card.Id, shuffle: false);
			_cardChoiceResolved = true;
			if (_messageLabel != null)
			{
				_messageLabel.Text = $"已加入卡牌：{card.Name}";
			}

			if (_cardContainer != null)
			{
				foreach (Button btn in _cardContainer.GetChildren().OfType<Button>())
				{
					btn.Disabled = true;
				}
			}

			if (_skipCardButton != null)
			{
				_skipCardButton.Disabled = true;
			}

			UpdateContinueButtonState();
		}

		private void OnSkipCardPressed()
		{
			_cardChoiceResolved = true;
			if (_messageLabel != null)
			{
				_messageLabel.Text = "已跳过卡牌奖励。";
			}

			if (_cardContainer != null)
			{
				foreach (Button btn in _cardContainer.GetChildren().OfType<Button>())
				{
					btn.Disabled = true;
				}
			}

			if (_skipCardButton != null)
			{
				_skipCardButton.Disabled = true;
			}

			UpdateContinueButtonState();
		}

		private void OnPotionClaimed(Button button, PotionDefinition potion)
		{
			if (_potionClaimed)
			{
				return;
			}

			GameRoot.Instance.PlayerPotions.Add(potion.Id);
			_potionClaimed = true;
			button.Disabled = true;
			if (_messageLabel != null)
			{
				_messageLabel.Text = $"获得药剂：{potion.Name}";
			}
			UpdateContinueButtonState();
		}

		private void OnRelicClaimed(Button button, RelicDefinition relic)
		{
			if (_relicClaimed)
			{
				return;
			}

			GameRoot.Instance.PlayerRelics.Add(relic.Id);
			_relicClaimed = true;
			button.Disabled = true;
			if (_messageLabel != null)
			{
				_messageLabel.Text = $"获得遗物：{relic.Name}";
			}
			UpdateContinueButtonState();
		}

		private void UpdateContinueButtonState()
		{
			if (_continueButton == null)
			{
				return;
			}

			var potionResolved = _bundle?.PotionId == null || _potionClaimed;
			var relicResolved = _bundle?.RelicId == null || _relicClaimed;

			_continueButton.Disabled = !_cardChoiceResolved || !potionResolved || !relicResolved;
		}

		private void OnContinuePressed()
		{
			RewardSystem.RewardStore.Clear();
			GameRoot.Instance.ChangeState(GameRoot.GameState.Map);
		}

		public override void _ExitTree()
		{
			base._ExitTree();
			RewardSystem.RewardStore.Clear();
		}
	}
}

